package com.mobilesales.android.activities.products;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.mobilesales.android.MobileSalesActivity;
import com.mobilesales.android.R;
import com.mobilesales.android.activities.ListModelActivity;
import com.mobilesales.android.adapters.ProductCategoryAdapter;
import com.mobilesales.android.database.ProductManager;
import com.mobilesales.android.infrastructure.ProductCategoryItem;
import com.mobilesales.android.model.products.Category;
import com.mobilesales.android.model.products.Product;
import com.mobilesales.android.util.Constants;
import com.mobilesales.android.util.FilterFieldWatcher;
import com.mobilesales.android.util.MessageBox;

public class Products extends ListModelActivity<ProductCategoryItem> {

	private List<Product> products;
	private List<Category> categories;
	private int currentCategoryId = 0;
	private Integer parentCategoryId = null;
	private ProductCategoryAdapter adapter = null;
	private FilterFieldWatcher filter;

	// private Button parentCatBtn;

	private EditText searchField;

	private int requestCode = 0;

	private Handler handler = new Handler();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.products);
		// parentCatBtn = (Button) this.findViewById(R.id.parentCatBtn);
		searchField = (EditText) this.findViewById(R.id.productFilterText);
		loadItems();
		Bundle bundle = this.getIntent().getExtras();
		if (bundle != null && bundle.containsKey(Constants.RequestCode)) {
			requestCode = bundle.getInt(Constants.RequestCode);
		}
		new com.mobilesales.android.adapters.SlidingMenus(this);

	}

	public void getParentCategory(View v) {
		if (parentCategoryId != null) {
			this.loadCategory(parentCategoryId);
		}
	}

	private void loadItems() {
		categories = this.getCategories();
		products = this.getProducts();
		if (categories != null && products != null) {
			loadCategory(currentCategoryId);
		} else {
			MessageBox.show(this, getString(R.string.ErrorProducts));
		}
	}

	@Override
	protected void onListItemClick(ListView listView, View view, int position,
			long id) {
		super.onListItemClick(listView, view, position, id);
		ProductCategoryItem prodCat = (ProductCategoryItem) this.adapter
				.getItem(position);
		if (prodCat.isCategory()) {
			this.loadCategory(prodCat.getCategory().Id);
		} else {
			Product prod = prodCat.getProduct();
			if (this.requestCode == Constants.RequestCodes.ChooseProduct) {
				Bundle bundle = new Bundle();
				bundle.putInt(Constants.ProductId, prod.Id);
				Intent intent = new Intent();
				intent.putExtras(bundle);
				setResult(RESULT_OK, intent);
				super.finish();
			} else {
				Intent intent = new Intent(this, DetailsProduct.class);
				intent.putExtra(Constants.ProductId, prod.Id);
				this.startActivity(intent);
			}
		}
	}

	private void loadCategory(int categoryId) {
		List<ProductCategoryItem> source = new ArrayList<ProductCategoryItem>();

		if (this.categories != null) {
			this.parentCategoryId = null;
			if (categoryId != 0) {
				for (Category c : categories) {
					if (c.Id == categoryId) {
						this.parentCategoryId = c.ParentId;
						break;
					}
				}
			}
		} else {
			MessageBox.show(this, getString(R.string.ErrorProducts));
			return;
		}

		this.currentCategoryId = categoryId;
		// parentCatBtn.setEnabled(currentCategoryId != 0);

		List<Category> categories = this.getCategories(categoryId);
		if (categories != null) {
			for (Category c : categories)
				source.add(new ProductCategoryItem(c));
		} else {
			MessageBox.show(this, getString(R.string.ErrorProducts));
			return;
		}

		List<Product> products = this.getProducts(categoryId);
		if (products != null) {
			for (Product p : products)
				source.add(new ProductCategoryItem(p));
		} else {
			MessageBox.show(this, getString(R.string.ErrorProducts));
			return;
		}

		this.setItemsSource(source);

	}

	@Override
	protected void setItemsSource(List<ProductCategoryItem> source) {
		adapter = new ProductCategoryAdapter(this, R.layout.product_list_item,
				source);
		this.setListAdapter(adapter);
		this.filter = new FilterFieldWatcher(this.adapter);
		this.searchField.addTextChangedListener(this.filter);
	}

	private List<Product> getProducts(int categoryId) {
		if (this.products != null) {
			List<Product> selectedProducts = new ArrayList<Product>();
			for (Product p : products) {
				List<Category> cats = p.Categories;
				if (cats != null) {
					for (Category c : cats)
						if (c.Id == categoryId)
							selectedProducts.add(p);
				}
			}
			return selectedProducts;
		}
		return null;
	}

	private List<Category> getCategories(int parentCategoryId) {
		if (this.categories != null) {
			List<Category> selectedCategories = new ArrayList<Category>();
			for (Category c : categories) {
				if (c.ParentId == null || c.ParentId == 0) {
					if (parentCategoryId == 0)
						selectedCategories.add(c);
				} else if (c.ParentId == parentCategoryId) {
					selectedCategories.add(c);
				}
			}
			return selectedCategories;
		}
		return null;
	}

	private List<Category> getCategories() {
		ProductManager manager = new ProductManager(this);
		List<Category> categories = manager.GetCategoryList();
		manager.Close();
		return categories;
	}

	private List<Product> getProducts() {
		ProductManager manager = new ProductManager(this);
		List<Product> products = manager.GetProductList();
		manager.Close();
		return products;
	}

	public void refresh() {
		handler.post(new Runnable() {
			public void run() {
				loadItems();
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (this.filter != null)
			this.searchField.removeTextChangedListener(this.filter);
	}

	@Override
	public void finish() {
		if (parentCategoryId != null)
			this.loadCategory(parentCategoryId);
		else
			super.finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuinf = new MenuInflater(this);
		menuinf.inflate(R.menu.product_menu, menu);
		if (parentCategoryId == null)
			onPrepareOptionsMenu(menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		{
			menu.getItem(1).setVisible(currentCategoryId != 0);
		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_product_home:
			Intent intent = new Intent(this, MobileSalesActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			break;
		case R.id.menu_product_back:
			getParentCategory(null);
			break;
		default:
			break;
		}
		return true;
	}
}
